#if 0
#include <unistd.h>
#include <stdio.h>

int main()
{
    int pipefd[2];
    char buf[20];
    // 创建管道
    if (pipe(pipefd) == -1) {
        perror("pipe");
        return 1;
    }
    // 写入数据到管道中
    write(pipefd[1], "Hello, pipe!", 13);
    // 从管道中读取数据
    read(pipefd[0], buf, 20);
    printf("Received message: %s\n", buf);
    // 关闭文件描述符
    close(pipefd[0]);
    close(pipefd[1]);
    return 0;
}
#endif

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BUFFER_SIZE 1024

int main()
{
    int fd[2];
    pid_t pid;
    char buffer[BUFFER_SIZE];

    // 创建匿名管道
    if (pipe(fd) < 0) {
        printf("Create pipe error!\n");
        return -1;
    }

    pid = fork();
    if (pid < 0) 
    {
        printf("Fork error!\n");
        return -1;
    } 
    else if (pid > 0)// 父进程写入数据
    {
        close(fd[0]); // 关闭读端
        while (1) 
        {
            fgets(buffer, BUFFER_SIZE, stdin);

            if (strcmp(buffer, "exit\n") == 0) 
            {
                break;
            }
            write(fd[1], buffer, strlen(buffer));
        }
        close(fd[1]); // 关闭写端
    } 
    else 
    { // 子进程读取数据
        close(fd[1]); // 关闭写端
        while (1) 
        {
            ssize_t count = read(fd[0], buffer, BUFFER_SIZE);
            if (count == 0)             
            {
                break;
            }
            buffer[count] = '\0';
            printf("Received message: %s", buffer);
        }
        close(fd[0]); // 关闭读端
    }
    return 0;
}